import os
import random
import subprocess
import time
import traceback

import numpy
import requests
from loguru import logger
from playwright.sync_api import sync_playwright
import single_login


class ChenFeng:
    def __init__(self, playwright, host, command):
        self.playwright = playwright
        self.host = host
        self.command = command
        self.login_func = single_login.Login(playwright, host, command)
        self.download_path = os.path.join(os.getcwd(), "download")
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)


    def run(self):
        self.login_func.login()
        # 所有文件的路径列表
        all_file_path_list = []
        # 获取右上角的所有公司，找到【寄售或者经销】的两个索引
        for i in range(60):
            if self.login_func.page.query_selector('span.current-supplier-name') is not None and self.login_func.page.query_selector(
                    'span.current-supplier-name').is_visible():
                break
            time.sleep(1)
        self.login_func.page.query_selector('span.current-supplier-name').click()
        dropdown_element_list = self.login_func.page.query_selector_all('div.dropdown-wrap')
        # 寄售索引
        jishou_index = -1
        # 经销索引
        jixiao_index = -1
        # 当前账号是寄售还是经销  0 是 经销 1 是 寄售
        current_type = ""
        for i in range(len(dropdown_element_list)):
            # 找到 ul
            if dropdown_element_list[i].query_selector('ul') is None:
                continue
            # 找到 ul 下的第二个div
            if dropdown_element_list[i].query_selector_all('ul >> div') is None and len(
                    dropdown_element_list[i].query_selector_all('ul >> div')) != 2:
                continue
            # 找到第一个div
            first_div = dropdown_element_list[i].query_selector('ul >> div:nth-child(1)')
            if '寄售' in first_div.text_content():
                logger.info("当前账号是寄售【{}】".format(first_div.text_content()))
                current_type = '1'
            elif '经销' in first_div.text_content():
                logger.info("当前账号是经销【{}】".format(first_div.text_content()))
                current_type = '0'
            # 获取第二个div
            second_div = dropdown_element_list[i].query_selector('ul >> div:nth-child(2)')
            # 获取div下的所有li
            li_list = second_div.query_selector_all('li')
            for j in range(len(li_list)):
                if jishou_index == -1 and "寄售" in li_list[j].inner_text():
                    logger.info("找到【寄售】下标【{}】".format(j))
                    jishou_index = j
                elif jixiao_index == -1 and "经销" in li_list[j].inner_text():
                    logger.info("找到【经销】下标【{}】".format(j))
                    jixiao_index = j
                if jishou_index != -1 and jixiao_index != -1:
                    break
            if current_type != "" and jishou_index != -1 and jixiao_index != -1:
                break
        # 点击【库存】
        self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("库存") >> a').click()
        logger.info("点击【库存】按钮...")
        # 去到【经销进销存台账】页面，找到【供应商名称】下拉框，并获取下拉框所有值
        frame = None
        for i in range(10):
            self.login_func.page.query_selector('div.river-origin-frame')
            frame = self.login_func.page.frame(name="iframe-page-2")
            if frame is not None:
                logger.info("找到【经销进销存台账】页面...")
                break
            try:
                logger.info("未找到【经销进销存台账】页面，可能是【库存】没有点击成功...")
                li_list = self.login_func.page.query_selector('ul.nav-menu-list').query_selector_all('li')
                for li in li_list:
                    if li.inner_text() == "库存":
                        li.click()
                        break
            except Exception as e:
                logger.info("点击【库存】按钮失败，重试...")
                pass
            time.sleep(1)
        for i in range(10):
            if frame.query_selector('span.next-select-inner') is not None:
                logger.info("找到【供应商名称】下拉框...")
                break
            time.sleep(1)
        frame.query_selector('span.next-select-inner').click()
        time.sleep(5)
        logger.info("点击【供应商名称】下拉框...")
        ul = frame.query_selector('ul.next-menu-content')
        li_list = ul.query_selector_all('li')
        logger.info("供应商名称下拉框有{}个选项...".format(len(li_list)))
        self.download_jxc(li_list, frame, all_file_path_list, "经销" if current_type == '0' else "寄售")
        # 切换页面
        self.login_func.page.query_selector('span.current-supplier-name').click()
        logger.info("点击右上角的公司按钮...")
        dropdown_element_list = self.login_func.page.query_selector_all('div.dropdown-wrap')
        dropdown_element = dropdown_element_list[0]
        # 获取第二个div下面的li
        li_list = dropdown_element.query_selector('ul >> div:nth-child(2)').query_selector_all('li')
        logger.info("当前账号是【{}】".format(("经销" if current_type == '0' else "寄售")))
        if current_type == '0':
            # 当前是经销
            logger.info("切换到【寄售】...")
            li_list[jishou_index].click()
            current_type = '1'
        else:
            # 当前是寄售
            logger.info("切换到【经销】...")
            li_list[jixiao_index].click()
            current_type = '0'
        time.sleep(5)
        self.wait(frame)
        # 检查是否有弹窗
        logger.info("检查是否有弹窗...")
        for i in range(10):
            if len(self.login_func.page.query_selector_all('a.ascp-frame-dialog-close:visible')) > 0:
                for dialog in self.login_func.page.query_selector_all('a.ascp-frame-dialog-close:visible'):
                    try:
                        dialog.click(timeout=3000)
                    except:
                        pass
            time.sleep(1)
            logger.info("等待【{}】秒，当前【{}】秒...".format(10, i + 1))
        # 点击【库存】按钮
        ul = self.login_func.page.query_selector('ul.nav-menu-list')
        li_list = ul.query_selector_all('li')
        # 是否点击库存标识
        has_click_kucun = False
        for i in range(len(li_list)):
            if "库存" == li_list[i].inner_text() and li_list[i].is_visible():
                li_list[i].click()
                has_click_kucun = True
                break
        if not has_click_kucun:
            logger.error("没有找到【库存】按钮...")
            logger.info("尝试点击【更多】按钮...")
            # 是否点击更多按钮
            has_click_more = False
            for i in range(len(li_list)):
                if li_list[i] is not None and \
                        li_list[i].inner_text() is not None and \
                        li_list[i].inner_text().startswith("更多"):
                    li_list[i].click()
                    time.sleep(1)
                    has_click_more = True
                    break
            if has_click_more:
                li_list = self.login_func.page.query_selector('ul.nav-more').query_selector_all('li')
                for i in range(len(li_list)):
                    if "库存" == li_list[i].inner_text():
                        li_list[i].click()
                        has_click_kucun = True
                        break
        if not has_click_kucun:
            logger.error("没有找到【库存】按钮...")
            self.close()
        self.wait(self.login_func.page)
        time.sleep(5)
        for i in range(20):
            self.login_func.page.query_selector('div.river-origin-frame')
            frame = self.login_func.page.frame(name="iframe-page-2")
            if frame is not None:
                break
            time.sleep(1)
        for i in range(10):
            if frame.query_selector('span.next-select-inner') is not None:
                break
            time.sleep(1)
        frame.query_selector('span.next-select-inner').click()
        ul = frame.query_selector('ul.next-menu-content')
        li_list = ul.query_selector_all('li')
        self.download_jxc(li_list, frame, all_file_path_list, "经销" if current_type == 0 else "寄售")
        logger.info("所有库存数据下载完成...")

    def download_jxc(self, li_list, frame, all_file_path_list, folder):
        for i in range(len(li_list)):
            try:
                self.click_carrier(i, frame)
                carrier_name = li_list[i].inner_text()
                logger.info("正在操作第{}个供应商：{}".format(i + 1, carrier_name))
                logger.info("先点击【查询】按钮查询数据...")
                with self.login_func.page.expect_response("*supplierPssIndex/querySupplierPssIndex*"):
                    frame.query_selector('button:has-text("查询")').click()
                # 点击【导出】按钮
                time.sleep(2)
                frame.query_selector('button:has-text("导出")').click()
                logger.info("点击【导出】按钮...")
                logger.info("等待【操作成功】弹窗出现...")
                for j in range(20):
                    if frame.query_selector('div:has-text("操作成功")') is not None:
                        logger.info("点击下载文件...")
                        with self.login_func.page.expect_download() as download_info:
                            frame.query_selector('a.J_notOpenInContainer').click()
                        download = download_info.value
                        file_path = os.path.join(os.getcwd(), "jxc_download")
                        if not os.path.exists(file_path):
                            os.mkdir(file_path)
                        file_path = os.path.join(file_path, folder)
                        if not os.path.exists(file_path):
                            os.mkdir(file_path)
                        file_path = os.path.join(file_path, carrier_name + ".xlsx")
                        if os.path.exists(file_path):
                            os.remove(file_path)
                        download.save_as(file_path)
                        all_file_path_list.append(file_path)
                        if "寄售" == folder:
                            uri = "/jxcJs/sysJxcJsImport"
                        else:
                            uri = "/jxcJx/sysJxcJxImport"
                        self.upload_file(uri, file_path)
                        time.sleep(1)
                        if frame.query_selector('button:has-text("关闭")') is not None and frame.query_selector(
                                'button:has-text("关闭")').is_visible():
                            frame.query_selector('button:has-text("关闭")').click()
                        if self.login_func.page.query_selector('button:has-text("关闭")') is not None and self.login_func.page.query_selector(
                                'button:has-text("关闭")').is_visible():
                            self.login_func.page.query_selector('button:has-text("关闭")').click()
                        logger.info("关闭弹窗...")
                        time.sleep(2)
                        with self.login_func.page.expect_response("*supplierPssIndex/querySupplierPssIndex*") as response_info:
                            frame.query_selector('button:has-text("清空")').click()
                            logger.info("点击【清空】按钮...")
                        break
                    else:
                        logger.info("等待【操作成功】弹窗出现，【{}】秒，当前【{}】秒...".format(20, j + 1))
                        time.sleep(1)
                        logger.info("检查是否没有数据...")
                        if frame.query_selector('div.next-table-empty') is not None and frame.query_selector(
                                'div.next-table-empty').is_visible():
                            logger.info("没有数据，操作下一个供应商...")
                            break
                # 获取文件名
            except Exception as e:
                logger.error("操作第{}个供应商：{}，失败，原因：{}".format(i + 1, li_list[i].inner_text(), e))
                continue

    def click_carrier(self, i, frame):
        if frame.query_selector('button:has-text("关闭")') is not None and frame.query_selector(
                'button:has-text("关闭")').is_visible():
            frame.query_selector('button:has-text("关闭")').click()
        if self.login_func.page.query_selector('button:has-text("关闭")') is not None and self.login_func.page.query_selector(
                'button:has-text("关闭")').is_visible():
            self.login_func.page.query_selector('button:has-text("关闭")').click()
        logger.info("关闭弹窗...")
        ul = frame.query_selector('ul.next-menu-content')
        if ul is None:
            frame.query_selector('span.next-select-inner').click()
            ul = frame.query_selector('ul.next-menu-content')
        li_list = ul.query_selector_all('li')
        li_list[i].click()

    def upload_file(self, uri, file_path):
        try:
            url = self.host + uri
            logger.info("正在上传文件到服务器【{}】：".format(url) + file_path)
            files = [
                ('file', (open(file_path, 'rb')))
            ]
            response = requests.request("POST", url, files=files)
            logger.info(response.text)
        except:
            traceback.print_exc()

    def wait(self, page, seconds=1):
        page.wait_for_load_state(state="domcontentloaded")
        time.sleep(seconds)

    def close(self):
        try:
            if self.login_func.page:
                self.login_func.page.close()
        except:
            pass
        try:
            if self.login_func.browser:
                self.login_func.browser.close()
        except:
            pass
        try:
            if self.login_func.context:
                self.login_func.context.close()
        except:
            pass


def main(host, command):
    with sync_playwright() as playwright:
        for i in range(6):
            try:
                chen_feng = ChenFeng(playwright, host, command)
                chen_feng.run()
                chen_feng.close()
                return True
            except:
                traceback.print_exc()
    return False

# host = "http://1.95.41.135:8990/api/v1"
# command = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --window-size=1600,1024 --remote-debugging-port=9001"
# main(host, command)
